import { Injectable } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import { Request } from 'express'

@Injectable()
export class AuthService {
  constructor(private jwtService: JwtService) {}

  /**
   * 生成JWT令牌
   * @param payload 要包含在令牌中的数据
   * @returns 生成的JWT令牌
   */
  generateToken(payload: JwtPayload): string {
    return this.jwtService.sign(payload)
  }

  /**
   * 验证JWT令牌
   * @param token 要验证的JWT令牌
   * @returns 如果令牌有效，返回解码后的payload，否则返回null
   */
  verifyToken(token: string): any {
    try {
      return this.jwtService.verify(token)
    } catch (error) {
      return null
    }
  }

  /**
   * 从请求头中提取Bearer令牌 
   * @param request - HTTP请求对象，包含认证头信息
   * @returns 如果找到Bearer类型的令牌，则返回该令牌字符串；否则返回undefined
   */
  static extractTokenFromHeader(request: Request): string | undefined {
    const [type, token] = request.headers.authorization?.split(' ') ?? []
    return type === 'Bearer' ? token : undefined
  }
}

interface JwtPayload {
  email: string
  sub: number
}
